package com.gh.mp.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gh.mp.edu.common.R;
import com.gh.mp.edu.utils.JwtUtils;
import com.gh.mp.eduservice.client.OrderClient;
import com.gh.mp.eduservice.client.VodClient;
import com.gh.mp.eduservice.entity.EduChapter;
import com.gh.mp.eduservice.entity.EduCourse;
import com.gh.mp.eduservice.entity.EduCourseDescription;
import com.gh.mp.eduservice.entity.EduVideo;
import com.gh.mp.eduservice.entity.form.CourseInfoForm;
import com.gh.mp.eduservice.entity.frontVo.CourseFrontVo;
import com.gh.mp.eduservice.entity.frontVo.CourseInfoFrontVo;
import com.gh.mp.eduservice.entity.query.QueryCourse;
import com.gh.mp.eduservice.entity.vo.CoursePublishVo;
import com.gh.mp.edu.exception.EduException;
import com.gh.mp.eduservice.mapper.EduCourseMapper;
import com.gh.mp.eduservice.service.EduChapterService;
import com.gh.mp.eduservice.service.EduCourseDescriptionService;
import com.gh.mp.eduservice.service.EduCourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gh.mp.eduservice.service.EduVideoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author Eric
 * @since 2021-04-24
 */
@Service
@Transactional
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Autowired
    private EduCourseDescriptionService descriptionService;

    @Autowired
    private EduChapterService eduChapterService;

    @Autowired
    private EduVideoService eduVideoService;

    @Autowired
    private EduCourseMapper eduCourseMapper;

    @Autowired
    private VodClient vodClient;

    @Autowired
    private OrderClient orderClient;

    @Override
    public String insertCourseInfo(CourseInfoForm courseInfoForm) {
        //1.课程基本信息添加到课程表
        //courseInfoForm数据复制到eduCourse里面去
        EduCourse eduCourse = new EduCourse();
        eduCourse.setSubjectParentId(courseInfoForm.getSubjectId());
        BeanUtils.copyProperties(courseInfoForm, eduCourse);
        eduCourse.setId(UUID.randomUUID().toString().replace("-", ""));
        int result = baseMapper.insert(eduCourse);
        //如果添加成功才进行下一步
        if (result > 0) {
            //2.课程描述信息添加到描述表
            EduCourseDescription eduCourseDescription = new EduCourseDescription();
            eduCourseDescription.setDescription(courseInfoForm.getDescription());
            eduCourseDescription.setId(eduCourse.getId());
            boolean flag = descriptionService.save(eduCourseDescription);
            if (flag) {
                return eduCourse.getId();
            }
        }
        return null;
    }

    @Override
    public CourseInfoForm getCourseInfoById(String id) {
        CourseInfoForm form = new CourseInfoForm();
        EduCourse eduCourse = baseMapper.selectById(id);
        if (eduCourse == null) {
            return form;
        }
        BeanUtils.copyProperties(eduCourse, form);
        EduCourseDescription eduCourseDescription = descriptionService.getById(id);
        form.setDescription(eduCourseDescription.getDescription());

        return form;
    }

    @Override
    public boolean updateCourseInfo(CourseInfoForm form) {
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(form, eduCourse);
        int result = baseMapper.updateById(eduCourse);
        if (result == 0) {
            throw new EduException(20001, "修改课程失败");
        }
        EduCourseDescription description = new EduCourseDescription();
        description.setId(form.getId());
        description.setDescription(form.getDescription());
        boolean flag = descriptionService.updateById(description);
        return flag;
    }

    @Override
    public IPage moreConditionPageList(Long page, Long limit, QueryCourse queryCourse) {
        Page<EduCourse> pageTeacher = new Page<>(page, limit);
        if (queryCourse == null) {
            IPage<EduCourse> eduCourseIPage = baseMapper.selectPage(pageTeacher, null);
            return eduCourseIPage;
        }
        String subjectId = queryCourse.getSubjectId();
        String subjectParentId = queryCourse.getSubjectParentId();
        String teacherId = queryCourse.getTeacherId();
        String title = queryCourse.getTitle();
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(subjectId)) {
            queryWrapper.eq("subject_id", subjectId);
        }
        if (!StringUtils.isEmpty(subjectParentId)) {
            queryWrapper.eq("subject_parent_id", subjectParentId);
        }
        if (!StringUtils.isEmpty(teacherId)) {
            queryWrapper.eq("teacher_id", teacherId);
        }
        if (!StringUtils.isEmpty(title)) {
            queryWrapper.like("title",title);
        }
        IPage<EduCourse> eduCourseIPage = baseMapper.selectPage(pageTeacher, queryWrapper);
        return eduCourseIPage;
    }

    @Override
    public Boolean deleteCourseById(String id) {
        //删除描述信息表
        descriptionService.removeById(id);
        QueryWrapper<EduChapter> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", id);
        List<EduChapter> list = eduChapterService.list(wrapper);
        if (list == null && list.size() == 0) {
            return true;
        }
        //把课程里面所有的视频都删除
        QueryWrapper<EduVideo> videoQueryWrapper=new QueryWrapper<>();
        videoQueryWrapper.eq("course_id",id);
        videoQueryWrapper.select("video_source_id");
        List<EduVideo> videoList = eduVideoService.list(videoQueryWrapper);
        List<String> videoIdList=new ArrayList<>();
        videoList.forEach(video->{
            String videoSourceId = video.getVideoSourceId();
            if(StringUtils.isEmpty(videoSourceId)){
                videoIdList.add(videoSourceId);
            }
        });
        if(videoIdList.size()>0){
            R result = vodClient.deleteBatch(videoIdList);
            if(result.getCode()==20001){
                throw new EduException(20001,"删除视频失败。熔断器");
            }
        }
        //获取到课程视频id
        QueryWrapper<EduVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id",id);
        eduVideoService.remove(queryWrapper);
//        list.stream().forEach(a -> {
//            String chapterId = a.getId();
//            queryWrapper.eq("course_id", id);
//            queryWrapper.eq("chapter_id", chapterId);
//            eduVideoService.remove(queryWrapper);//删小节
//        });
        eduChapterService.remove(wrapper);//删章节
        int i = baseMapper.deleteById(id);//删课程
        return i > 0;
    }

    @Override
    public CoursePublishVo getAllCourseInfo(String id) {
        CoursePublishVo coursePublishVo=eduCourseMapper.getAllCourseInfo(id);
        return coursePublishVo;
    }

    @Override
    public Boolean publishCourseByCourseId(String id) {
        EduCourse eduCourse=new EduCourse();
        eduCourse.setId(id);
        eduCourse.setStatus("Normal");
        int i = baseMapper.updateById(eduCourse);
        return i>0;
    }

    @Override
    public Map<String, Object> getFrontCourseList(Page<EduCourse> pageCourse, CourseFrontVo courseFrontVo) {
        QueryWrapper<EduCourse> queryWrapper=new QueryWrapper<>();
        if(!StringUtils.isEmpty(courseFrontVo.getSubjectParentId())){
            queryWrapper.eq("subject_parent_id",courseFrontVo.getSubjectParentId());
        }
        if(!StringUtils.isEmpty(courseFrontVo.getSubjectId())){
            queryWrapper.eq("subject_id",courseFrontVo.getSubjectId());
        }
        if(!StringUtils.isEmpty(courseFrontVo.getBuyCountSort())){
            queryWrapper.orderByDesc("buy_count");
        }
        if(!StringUtils.isEmpty(courseFrontVo.getGmtCreateSort())){
            queryWrapper.orderByDesc("gmt_create");
        }
        if(!StringUtils.isEmpty(courseFrontVo.getPriceSort())){
            queryWrapper.orderByDesc("price");
        }
        baseMapper.selectPage(pageCourse,queryWrapper);
        List<EduCourse> records = pageCourse.getRecords();
        long total = pageCourse.getTotal();
        long current = pageCourse.getCurrent();
        long size = pageCourse.getSize();
        boolean hasPrevious = pageCourse.hasPrevious();
        boolean hasNext = pageCourse.hasNext();
        Map<String,Object> map=new HashMap<>();
        map.put("records",records);
        map.put("total",total);
        map.put("current",current);
        map.put("size",size);
        map.put("hasPrevious",hasPrevious);
        map.put("hasNext",hasNext);
        map.put("pages",pageCourse.getPages());
        return map;
    }

    @Override
    public CourseInfoFrontVo getFrontCourseInfo(String id) {
        CourseInfoFrontVo courseInfoFrontVo=eduCourseMapper.getFrontCourseInfo(id);
        return courseInfoFrontVo;
    }

    @Override
    public Boolean isBuy(String courseId, HttpServletRequest request) {
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if(StringUtils.isEmpty(memberId)) {
            throw new EduException(20001,"未登录");
        }
        Boolean isBuy = orderClient.isBuyCourse(courseId, memberId);
        return isBuy;
    }
}
